<template>
  <div class="app-container">
    <div id="map">
      <Map
        :deviceCategoryList="deviceCategoryList"
        :receiveAlarmData="tableData.value"
        :alarmAttribute="alarmAttributeData"
        v-if="showMap"
      />
      <Widgets
        :deviceCategoryList="deviceCategoryList"
        :receiveAlarmData="tableData.value"
      />
    </div>
    <!-- <el-row class="tool">
      <el-col :span="6">
        <el-input
          v-model="queryParams.KeyWords"
          placeholder="请输入任务名称搜索"
        >
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </el-col>
    </el-row> -->

    <div
      v-if="showLayer"
      class="content-danger-region"
      :style="{ width: deviceTag ? '560px' : '0px' }"
    >
      <b class="deviceTag" @click="deviceTag = !deviceTag">
        <i-ep-ArrowLeft v-if="!deviceTag" class="text-size-[1vh] v-middle" />
        <i-ep-ArrowRight v-if="deviceTag" class="text-size-[1vh] v-sub" />
        {{ !deviceTag ? "展开" : "收缩" }}
      </b>
      <div v-if="deviceTag">
        <el-popover
          placement="bottom"
          :width="400"
          trigger="click"
          @show="f_ClickDeviceTable"
        >
          <template #reference>
            <span class="filter">
              <box-icon color="red" size="24px" name="sort-up" class="v-top" />
            </span>
          </template>
          <el-table
            :data="pointData"
            ref="multipleTableRef"
            border
            header-row-class-name="table-header"
            @selection-change="f_HandleSelectionChange"
            height="380"
          >
            <el-table-column
              type="index"
              width="60"
              align="center"
              label="序号"
            />
            <!-- <el-table-column type="selection" width="50" align="center" /> -->
            <el-table-column
              prop="className"
              align="center"
              label="设备类型名称"
            />
            <el-table-column
              prop="className"
              align="center"
              label="是否显示"
              width="80"
            >
              <template #default="scope">
                <el-checkbox
                  v-model="scope.row.check"
                  size="large"
                  @change="f_ChangeCheck(scope.row, scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-popover>
        <div class="device">
          <el-row>
            <el-col
              v-for="(item, index) in pointSelectData"
              :key="index"
              :span="5"
              @click="f_ClickDevice(index)"
              :class="{ activeDevice: index == activeDevice }"
              >{{
                item.className.length > 5
                  ? item.className.substr(0, 5) + "..."
                  : item.className
              }}</el-col
            >
          </el-row>
        </div>
        <div class="table">
          <el-tabs v-model="activeTab" @tab-click="f_Tab">
            <el-tab-pane :label="'全部(' + totalNumber + ')'" name="">
              <el-table
                :data="tableData.value"
                border
                header-row-class-name="table-header"
                ref="tableLineRef"
                size="small"
                :height="tableHeightLayer"
                highlight-current-row
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                />

                <el-table-column
                  label="设备名称"
                  prop="pointName"
                  align="center"
                  width="160"
                >
                  <template #default="scope">
                    <span
                      style="color: #2196f3"
                      @click="f_OpenEchart(scope.row)"
                      >{{ scope.row.pointName }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  v-for="(item, index) in attrTitleData"
                  :key="index"
                  :prop="'attr' + index"
                  :label="item"
                  align="center"
                  show-overflow-tooltip
                  width="80"
                />
              </el-table>
              <pagination
                size="small"
                v-if="total > 0"
                v-model:total="total"
                v-model:page="queryParams.pageIndex"
                v-model:limit="queryParams.pageSize"
                @pagination="f_HandelQueryList"
              />
            </el-tab-pane>
            <el-tab-pane
              :label="'正常(' + f_GetStatusNumber('1') + ')'"
              name="1"
            >
              <el-table
                :data="tableData.value"
                border
                header-row-class-name="table-header"
                ref="tableLineRef"
                size="small"
                :height="tableHeightLayer"
                highlight-current-row
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                />

                <el-table-column
                  label="设备名称"
                  prop="pointName"
                  align="center"
                  width="160"
                >
                  <template #default="scope">
                    <span
                      style="color: #2196f3"
                      @click="f_OpenEchart(scope.row)"
                      >{{ scope.row.pointName }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  v-for="(item, index) in attrTitleData"
                  :key="index"
                  :prop="'attr' + index"
                  :label="item"
                  align="center"
                  show-overflow-tooltip
                  width="80"
                />
              </el-table>
              <pagination
                size="small"
                v-if="total > 0"
                v-model:total="total"
                v-model:page="queryParams.pageIndex"
                v-model:limit="queryParams.pageSize"
                @pagination="f_HandelQueryList"
              />
            </el-tab-pane>
            <el-tab-pane
              :label="'报警(' + f_GetStatusNumber('2') + ')'"
              name="2"
            >
              <el-table
                :data="tableData.value"
                border
                header-row-class-name="table-header"
                ref="tableLineRef"
                size="small"
                :height="tableHeightLayer"
                highlight-current-row
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                />

                <el-table-column
                  label="设备名称"
                  prop="pointName"
                  align="center"
                  width="160"
                >
                  <template #default="scope">
                    <span
                      style="color: #2196f3"
                      @click="f_OpenEchart(scope.row)"
                      >{{ scope.row.pointName }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  v-for="(item, index) in attrTitleData"
                  :key="index"
                  :prop="'attr' + index"
                  :label="item"
                  align="center"
                  show-overflow-tooltip
                  width="80"
                />
              </el-table>
              <pagination
                size="small"
                v-if="total > 0"
                v-model:total="total"
                v-model:page="queryParams.pageIndex"
                v-model:limit="queryParams.pageSize"
                @pagination="f_HandelQueryList"
              />
            </el-tab-pane>

            <el-tab-pane
              :label="'离线(' + f_GetStatusNumber('3') + ')'"
              name="3"
            >
              <el-table
                :data="tableData.value"
                border
                header-row-class-name="table-header"
                ref="tableLineRef"
                size="small"
                :height="tableHeightLayer"
                highlight-current-row
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                />

                <el-table-column
                  label="设备名称"
                  prop="pointName"
                  align="center"
                  width="160"
                >
                  <template #default="scope">
                    <span
                      style="color: #2196f3"
                      @click="f_OpenEchart(scope.row)"
                      >{{ scope.row.pointName }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  v-for="(item, index) in attrTitleData"
                  :key="index"
                  :prop="'attr' + index"
                  :label="item"
                  align="center"
                  show-overflow-tooltip
                  width="80"
                />
              </el-table>
              <pagination
                size="small"
                v-if="total > 0"
                v-model:total="total"
                v-model:page="queryParams.pageIndex"
                v-model:limit="queryParams.pageSize"
                @pagination="f_HandelQueryList"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>

    <!-- 详细数据 弹框 -->
    <el-drawer
      v-model="dialog.visible"
      title="设备上报数据"
      size="1200px"
      @close="f_CloseDialog"
      class="bg-[#f5f5f5!important]"
    >
      <detail_drawer />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Inspection",
  inheritAttrs: false,
});
import Map from "./components/Map/index.vue";
import Widgets from "./components/Widgets/index.vue";
// import Widgets from "./../../layer/area/components/Widgets/index.vue";
import { useDeviceCategory } from "@/views/layer/gismap/hooks/useDeviceCategory";
import { find } from "lodash";
import DeviceCategoryApi from "@/api/DeviceCategoryApi";
import { Search } from "@element-plus/icons-vue";
import DangerAPI from "@/api/DangerAPI";
import moment from "moment";
import LineAPI from "@/api/LineAPI";
import GisPointInfoAPI from "@/api/GisPointInfoAPI";

import { queryAreaInfoList } from "@/api/pipe";

import { LMap, LTileLayer } from "@vue-leaflet/vue-leaflet";
import { LMarker, LIcon } from "@vue-leaflet/vue-leaflet";
import { LPolygon, LPolyline } from "@vue-leaflet/vue-leaflet";

import PipeMarkerList from "./MarkerList/index.vue";
import PipePolylineList from "./PolylineList/index.vue";
import detail_drawer from "./../device/detail.vue";
const deviceCategoryList = ref();
const alarmAttributeData = ref([]);

const tablePointTypeData = ref([]);

// 隐患图片
const dangerLevel1 = ref(
  new URL(`../../../assets/device/point-2.png`, import.meta.url).href
);
const dangerLevel2 = ref(
  new URL(`../../../assets/device/point-2.png`, import.meta.url).href
);
const dangerLevel3 = ref(
  new URL(`../../../assets/device/point-3.png`, import.meta.url).href
);

let activeDevice = ref(0);
let tableHeight = ref(0);
let tableHeightLayer = ref(0);
let activeTag = ref(1);
const tableData = reactive({ value: [] });
const flagShowPopoer = ref(true);
const totalNumber = ref(0);
const deviceStatusData = ref([]);
const attrTitleData = ref([]);
const total = ref(0);

// 管点
const pointData = ref([]);
const pointSelectData = ref([]);

const tableLineData = ref([]);
const tablePointData = ref([]);
const tableDangerData = ref([]);
const tablePersonData = ref([]);

const tableLineRef = ref();
const tableDangerRef = ref();
const tablePersonRef = ref();
const multipleTableRef = ref();

const checkedLineData = ref([]);
const checkedDangerData = ref([]);
const checkedPersonData = ref([]);

const showDangerList = ref(false);
const showDangerDetail = ref(false);
const showLayer = ref(true);
const dangerDetailData = ref([]);
const activeDanger = ref({});
const queryParams = reactive({
  pageIndex: 1,
  pageSize: 10,
});
const selectData = ref([]);
const activeTab = ref("");
const lineData = ref([]);
const areaPolygonList = ref([]);

const deviceTag = ref(true);

const zoom = ref(12);

const dialog = reactive({
  visible: false,
});

const showMap = ref(true);

// 折线图
function f_OpenEchart() {
  dialog.visible = true;
}

// 关闭弹框
function f_CloseDialog() {
  dialog.visible = false;
}

// 勾选设备类型
function f_HandleSelectionChange(data, data2) {
  let mydata = multipleTableRef.value.getSelectionRows();
  // if (data.length == 0) {
  //   pointSelectData.value = pointData.value[0];
  //   ElMessage.error("至少勾选1种设备类型！");
  // } else if (data.length > 4) {
  //   pointSelectData.value = data.slice(0, 4);
  //   ElMessage.error("最多选择4种设备类型！");
  //   sessionStorage.setItem(
  //     "pointSelectData",
  //     JSON.stringify(pointSelectData.value)
  //   );
  //   return;
  // }

  pointSelectData.value = data;

  sessionStorage.setItem(
    "pointSelectData",
    JSON.stringify(pointSelectData.value)
  );
}

// 查询
function f_HandelQueryPointType() {
  const params1 = {
    pageSize: 1000,
    pageIndex: 1,
    pClassId: "01",
    isCollection: true,
  };
  DeviceCategoryApi.api_query(params1).then(({ data, errors, succeeded }) => {
    if (succeeded) {
      pointData.value = data.items;
      pointSelectData.value = pointData.value.slice(0, 4);
      pointSelectData.value = sessionStorage.getItem("pointSelectData")
        ? JSON.parse(sessionStorage.getItem("pointSelectData"))
        : pointData.value.slice(0, 4);

      if (sessionStorage.getItem("pointSelectData")) {
        pointSelectData.value = JSON.parse(
          sessionStorage.getItem("pointSelectData")
        );
      } else {
        pointSelectData.value = pointData.value.slice(0, 4);
      }
      // alarmAttributeData.value = pointSelectData.value[0].colAttribute;
      if (typeof pointSelectData.value[0].colAttribute == "string") {
        alarmAttributeData.value = pointSelectData.value[0].colAttribute;
      } else {
        alarmAttributeData.value = JSON.stringify(
          pointSelectData.value[0].colAttribute
        );
      }

      f_HandelQueryList();
      f_HandelQueryDeviceStatus();
    }
  });
}

// 查询 设备对应的明细
function f_HandelQueryList() {
  attrTitleData.value = [];
  const params = {
    pageSize: queryParams.pageSize,
    pageIndex: queryParams.pageIndex,
    classId: pointSelectData.value[activeDevice.value].classId,
  };
  if (activeTab.value) {
    params.deviceStatus = Number(activeTab.value);
  }
  GisPointInfoAPI.api_query_device_status_receivejson(params).then(
    ({ data, succeeded }) => {
      if (succeeded) {
        tableData.value = data.items;
        total.value = data.totalCount;
        if (
          !Object.keys(pointSelectData.value[activeDevice.value].colAttribute)
            .length
        ) {
          return;
        }

        tableData.value.forEach((ele, index) => {
          let num = 0;
          pointSelectData.value[activeDevice.value].colAttribute.forEach(
            (item) => {
              if (item.IsShow) {
                if (!index) {
                  attrTitleData.value.push(item.AttrName);
                }
                if (ele.receiveJson) {
                  tableData.value[index]["attr" + num] = JSON.parse(
                    ele.receiveJson
                  )[item.AttrKey];
                } else {
                  tableData.value[index]["attr" + num] = "";
                }
                num++;
              }
            }
          );
        });

        tableData.value = JSON.parse(JSON.stringify(tableData.value));

        attrTitleData.value = JSON.parse(
          JSON.stringify(attrTitleData.value)
        ).splice(0, 4);
      }
    }
  );
}

// 返回对应状态的设备数量
function f_GetStatusNumber(statusStr) {
  let deviceNumber = 0;
  let data = find(deviceStatusData.value, { deviceStatus: statusStr });
  if (data) {
    deviceNumber = data.num;
  }
  return deviceNumber;
}

// 查询
function f_HandelQueryDeviceStatus() {
  totalNumber.value = 0;
  const params = {
    pageSize: 1000,
    pageIndex: 1,
    classId: pointSelectData.value[activeDevice.value].classId,
  };
  GisPointInfoAPI.api_query_device_status(params).then(
    ({ data, errors, succeeded }) => {
      if (succeeded) {
        deviceStatusData.value = data;
        data.forEach((item) => {
          totalNumber.value += item.num;
        });
      }
    }
  );
}

// 点击过滤
function f_ClickDeviceTable() {
  pointData.value.forEach((item, index) => {
    let isCheck = find(pointSelectData.value, { id: item.id });
    if (isCheck) {
      pointData.value[index].check = true;
    }
  });
}

// 勾选
function f_ChangeCheck(data, index) {
  if (data.check) {
    if (pointSelectData.value.length + 1 > 4) {
      pointData.value[index].check = false;
      ElMessage.error("最多选择4种设备类型！");
      return;
    }

    let isRepeat = find(pointSelectData.value, { id: data.id });
    if (!isRepeat) {
      pointSelectData.value.push(data);
    }
  } else {
    let delIndex = 0;
    if (pointSelectData.value.length <= 1) {
      ElMessage.error("至少选择1种设备类型！");
      data.check = true;
      let isRepeat = find(pointSelectData.value, { id: data.id });
      if (!isRepeat) {
        pointSelectData.value.push(data);
      }

      // pointSelectData.value.push(data);
      return;
    } else {
      pointSelectData.value.forEach((item, index) => {
        if (item.id == data.id) {
          delIndex = index;
        }
      });
      pointSelectData.value.splice(delIndex, 1);
    }
  }

  sessionStorage.setItem(
    "pointSelectData",
    JSON.stringify(pointSelectData.value)
  );

  activeTab.value = "first";
  f_ClickDevice(0);
}

// 点击切换设备
function f_ClickDevice(index) {
  activeDevice.value = index;
  activeTab.value = "";
  if (typeof pointSelectData.value[index].colAttribute == "string") {
    alarmAttributeData.value = pointSelectData.value[index].colAttribute;
  } else {
    alarmAttributeData.value = JSON.stringify(
      pointSelectData.value[index].colAttribute
    );
  }

  showMap.value = false;
  f_HandelQueryDeviceStatus();

  setTimeout(() => {
    showMap.value = true;
    f_HandelQueryList();
  }, 200);
}

// 切换图层 Tab
function f_Tab(data) {
  activeTab.value = data.paneName;
  f_HandelQueryList();
}

window.onresize = () => {
  return (() => {
    tableHeight.value = window.innerHeight - 316;
  })();
};

onMounted(() => {
  // f_HandelQuery();
  // f_HandleQueryPointLineType();
  // f_HandelQueryLine();
  // getAllAreas();
  f_HandelQueryPointType();
  tableHeight.value = window.innerHeight - 316;
  tableHeightLayer.value = window.innerHeight - 288;
});
onBeforeMount(async () => {
  deviceCategoryList.value = await useDeviceCategory();
});
</script>
<style scoped lang="scss">
.app-container {
  position: relative;
}

#map {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  width: 100%;
  height: 100%;
}

.tool {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 100;
  width: 100%;
  padding: 8px;
  padding-right: 10px;

  .el-col-8 {
    button {
      width: 60px;
      height: 60px;
      font-size: 12px;
      border-radius: 50%;

      :deep span {
        display: inline-block;
      }

      p {
        display: block;
        width: 100%;
        margin: 6px 0;
      }
    }
  }
}

.content-danger-region {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 100;
  // width: 560px;
  height: calc(100%);
  background: #ffffffa1;

  .device {
    padding: 10px 10px 8px;
    background: #03a9f4;
    font-size: 14px;

    :deep .el-col {
      color: #fff;
      cursor: pointer;
    }

    .activeDevice {
      // font-weight: bold;
      color: #ffc107;
    }
  }

  .filter {
    position: absolute;
    top: 16px;
    right: 16px;
    z-index: 10000;
    cursor: pointer;
  }

  > div {
    width: 100%;
  }

  .title {
    height: 40px;
    line-height: 40px;
    color: #fff;
    text-align: center;
    background: linear-gradient(90deg, #299dda, #299dda);
  }

  .search {
    padding: 12px 12px 0;
  }

  .table {
    width: 100%;
  }

  :deep .el-form--inline .el-form-item {
    width: 100%;
  }

  :deep .el-tabs {
    padding: 10px;
    background: #535353a8;

    .el-tabs__item.is-active {
      border-bottom: none;
    }
  }
}

.content-danger-detail {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 100;
  width: calc(100% - 580px);
  height: 400px;
  background: #ffffffa1;

  > div {
    width: 100%;
  }

  .title {
    height: 40px;
    padding-left: 20px;
    line-height: 40px;
    color: #fff;
    text-align: left;
    background: linear-gradient(90deg, #299dda, #299dda);
  }

  .search {
    padding: 12px 12px 0;
  }

  .table {
    width: 100%;
    padding: 12px;
  }

  :deep .el-form--inline .el-form-item {
    width: 100%;
  }

  .active {
    border-bottom: 1px solid red;
  }
}
:deep .table-header .el-checkbox {
  display: none;
}
.deviceTag {
  position: absolute;
  top: 40%;
  left: -22px;
  width: 22px;
  font-size: 12px;
  font-weight: normal;
  line-height: 1.8vh;
  color: #15256b;
  text-align: center;
  cursor: pointer;
  background: rgba(102, 172, 253, 0.808);
  padding: 10px 4px;
}
</style>
